package cn.amoqi.springboot.validator.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ExceptionAdvice {

    private Logger logger = LoggerFactory.getLogger(getClass());

    //处理异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        StringBuilder sb = new StringBuilder();
        for (FieldError fieldError:e.getBindingResult().getFieldErrors()){
            sb.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append("\n");
        }
        logger.error(sb.toString(), e);
        //这个地方可以返回一个通用的类型
        return sb.toString();
    }
}
